//
//  ScanAddPartnerViewController.m
//  beautyLamp
//
//  Created by Tam Kwok To Michael on 2017/8/21.
//  Copyright © 2017年 Tam Kwok To Michael. All rights reserved.
//

#import "ScanAddPartnerViewController.h"
#import "BLHeader.h"
#import <AVFoundation/AVFoundation.h>
#import "SearchNet.h"
#import <MBProgressHUD.h>

@interface ScanAddPartnerViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, AVCaptureMetadataOutputObjectsDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *rectImageView;
@property (nonatomic, assign) CGFloat X;
@property (nonatomic, assign) CGFloat Y;
@property (nonatomic, assign) BOOL upOrDown; //up == yes, down = NO;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIImageView *line;
@property (nonatomic, assign) CGFloat lineY;
@property (nonatomic, assign) CGRect rectImageFrame;
@property (nonatomic, strong) CAShapeLayer *grayLayer;

@property (strong,nonatomic) AVCaptureDevice * device;
@property (strong,nonatomic) AVCaptureDeviceInput * input;
@property (strong,nonatomic) AVCaptureMetadataOutput * output;
@property (strong,nonatomic) AVCaptureSession * session;
@property (strong,nonatomic) AVCaptureVideoPreviewLayer * preview;

@end

@implementation ScanAddPartnerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self addGrayLayer:self.rectImageFrame];
    [self performSelector:@selector(setUPCamera) withObject:nil afterDelay:0.1];
}


- (void)setupUI {
    self.title = @"扫一扫";
    //self.edgesForExtendedLayout = UIRectEdgeNone;
//    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithTitle:@"相册" style:UIBarButtonItemStylePlain target:self action:@selector(openCamara)];
//    [right setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:kAppThemeColor ,NSForegroundColorAttributeName, nil] forState:UIControlStateNormal];
//    self.navigationItem.rightBarButtonItem = right;   
    //CGRect frame = self.rectImageView.frame;
    _X = (KScreenWidth - 220) * 0.5;
    _Y = (KScreenHeight - 220) * 0.5;
    self.rectImageFrame = CGRectMake(_X, _Y, 220, 220);
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(_X, _Y +5, 220, 2)];
    _line.image = [UIImage imageNamed:@"line"];
    self.lineY = self.Y;
    [self.view addSubview:_line];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.015 target:self selector:@selector(lineAnimal) userInfo:nil repeats:YES];
    self.upOrDown = NO;
}

- (void)addGrayLayer:(CGRect) rect{
    _grayLayer = [[CAShapeLayer alloc] init];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, nil, rect);
    CGPathAddRect(path, nil, CGRectMake(0, 0, KScreenWidth, KScreenHeight));
    [_grayLayer setFillRule:kCAFillRuleEvenOdd];
    [_grayLayer setPath:path];
    [_grayLayer setFillColor:[UIColor blackColor].CGColor];
    [_grayLayer setOpacity:0.6];
    [_grayLayer setNeedsDisplay];
    [self.view.layer addSublayer:_grayLayer];
}

- (void)lineAnimal {
    if (_upOrDown) {
        self.lineY = _lineY - 1;
        self.upOrDown = self.lineY > self.Y + 5 ? YES : NO;
    }else {
       self.lineY = _lineY + 1;
        self.upOrDown = self.lineY > self.Y + 215 ? YES : NO;
    }
    self.line.frame = CGRectMake(self.X, self.lineY, 220, 2);
}

- (void)setUPCamera {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device==nil) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //设置扫描区域
    CGFloat top = self.Y/KScreenHeight;
    CGFloat left = self.X/KScreenWidth;
    CGFloat width = 220/KScreenWidth;
    CGFloat height = 220/KScreenHeight;
    ///top 与 left 互换  width 与 height 互换
    [_output setRectOfInterest:CGRectMake(top,left, height, width)];
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    // 条码类型 AVMetadataObjectTypeQRCode
    [_output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode, nil]];
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame =self.view.layer.bounds;
    [self.view.layer insertSublayer:_preview atIndex:0];
    // Start
    [_session startRunning];
}

- (void)openCamara {
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.allowsEditing = YES;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        [self presentViewController:imagePicker animated:YES completion:^{
        }];
    }else{
        //NSLog(@"不能打开相册");
    }
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary<NSString *,id> *)editingInfo {
   
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    NSString *stringValue;
    if ([metadataObjects count] >0) {
        //停止扫描
        [_session stopRunning];
        [_timer setFireDate:[NSDate distantFuture]];
        
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        //NSLog(@"扫描结果：%@",stringValue);
        [self dealWithScanResult:stringValue];
        
       // NSArray *arry = metadataObject.corners;
    }
//    } else {
//        //NSLog(@"无扫描信息");
//        return;
//    }
}


- (void)dealWithScanResult:(NSString *)result {
    [SearchNet scanAddPartner:result completer:^(id result, NSError *error) {
        if(result) {
            [[NSNotificationCenter defaultCenter] postNotificationName:ADDPARTNERNOTIFICATION object:result];
            [self.navigationController popViewControllerAnimated:YES];
        }else {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.label.text = [error localizedDescription];
            [hud hideAnimated:YES afterDelay:2];
        }
    }];
}

- (void)dealloc {
    [self.timer invalidate];
    self.timer = nil;
}
@end
